<?php

namespace app\common\model;

use app\common\util\ErrorCode;
use app\common\util\Tools;
use think\Model;

/**
 * Class Auth
 * @package app\common\model
 * 优惠券表
 */
class trCoupon extends Model
{
    protected $pk = 'id';
    protected $resultSetType = 'collection'; //申明结果集是数据集对象（collection），查询结果才能用toArray()方法转为数组
    protected $name = "coupon"; //表名
    public $havingData = []; //存放已经获取的数据，减少数据库查询次数

    protected $type = [
        'create_time'  =>  'timestamp:Y-m-d H:i',
    ];

    public function transferField($data){
        if(!$data){
            return [];
        }
        $data = Tools::transferFields($data);
        if(isset($data[0])){
            foreach ($data as $k => $item){
                if(isset($item["type"])){
                    $data[$k]["typeText"] = $this->getAttrByType($item["type"]);
                }
                if (isset($item['mold'])){
                    $data[$k]["moldText"] = $this->getAttrByMold($item["mold"]);
                }
            }
        }else{
            if(isset($data["type"])){
                $data["typeText"] = $this->getAttrByType($data["type"]);
            }
            if(isset($data['mold'])){
                $data["moldText"] = $this->getAttrByMold($data["mold"]);
            }
        }
        return $data;
    }

    public function getAttrByType($type){ // 类型，1：机场接送、2：巴士线路、3：专车接送、0通用，4包车线路
        switch ($type){
            case "1":
                $text = "机场接送";
                break;
            case "2":
                $text = "巴士线路";
                break;
            case "3":
                $text = "专车接送";
                break;
            case "0":
                $text = "通用";
                break;
            case "4":
                $text = "包车线路";
                break;
            default:
                $text = "其它";
                break;
        }
        return $text;
    }

    public function getAttrByMold($mold){ // 获取方式，1：普通优惠券、2：推荐优惠券、3：被推荐优惠券
        switch ($mold){
            case "1":
                $text = "普通优惠券";
                break;
            case "2":
                $text = "推荐优惠券";
                break;
            case "3":
                $text = "被推荐优惠券";
                break;
            default:
                $text = "其它优惠券";
                break;
        }
        return $text;
    }

    //分页获取所有字段数据
    public function getList($field = '*', $filter = [], $page = 1, $limit = 10, $order = "create_time desc", $paginate = true){
        $db = self::where($filter)->field($field)->order($order);
        if($paginate){
            $data = $db->paginate(array('page' => $page, 'list_rows' => $limit));
            if($data){
                $data = $data->toArray();
                $data["data"] = $this->transferField($data["data"]);
                return $data;
            }
        }else{
            if($page && $limit)
                $db->limit($page-1, $limit);
            $data = $db->select();
            $data = $this->transferField($data->toArray());
            return $data;
        }
        return [];
    }

    //根据条件获取数量
    public function getCount($filter){
        if(!empty($filter)){
            return self::where($filter)->count();
        }else{
            return self::count();
        }
    }

    // 操作数据库的数据检查
    public function pre_data_check($data){
        $result = Tools::checkDataBaseFields(self::getTable(), $data);
        if(isset($result["code"])){
            return $result;
        }
        return true;
    }

    //添加
    public function add($data, $getId=false){
        if(!$data)
            return true;
        $result = $this->pre_data_check($data);
        if(isset($result["code"])){
            return $result;
        }
        $data["mall_id"] = request()->mallData["id"];
        if(empty($data["create_time"])) $data["create_time"] = time();
        if($getId){
            return self::insertGetId($data);
        }else{
            return self::insert($data);
        }
    }

    //更新
    public function doUpdate($data, $filter = []){
        if(!$data)
            return true;
        $result = $this->pre_data_check($data);
        if(isset($result["code"])){
            return $result;
        }
        if(self::save($data, $filter)){
            return true;
        }else{
            return false;
        }
    }

    //获取某字段的值
    public function getValue($field, $filter = []){
        if(!is_array($field)){
            return self::where($filter)->value($field);
        }
        return false;
    }

    //获取某字段的所有值
    public function getColumn($field, $filter = [], $key = ''){
        if(!is_array($field)){
            return self::where($filter)->column($field, $key);
        }
        return [];
    }

    //获取多字段数据
    public function getFields($field, $filter = [], $one = true, $toArray = true){ //缓存方法：缓存所有字段，只返回需要的字段
        if($one){
            $data = self::where($filter)->field($field)->find();
            return $data ? ($toArray ? $this->transferField($data->toArray()) : Tools::transferFields($data->getData())) : [];
        }else{
            $data = self::where($filter)->field($field)->select();
            return $data ? ($toArray ? $this->transferField($data->toArray()) : $data) : [];
        }
    }

    //根据ID删除数据
    public function delById($id){
        if(is_array($id)){
            if($this->getCount([["id", "in", $id], ["time_from", "<", time()], ["time_to", ">", time()]])){
                return ErrorCode::code("customized", "优惠券处于活动中，无法删除");
            }
            $result = self::where('id', 'in', $id)->delete();
        }else{
            if($this->getCount([["id", "=", $id], ["time_from", "<", time()], ["time_to", ">", time()]])){
                return ErrorCode::code("customized", "优惠券处于活动中，无法删除");
            }
            $result = self::where('id', $id)->delete();
        }
        return $result;
    }
}